using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using StupidSpaceThing;

namespace RacerGame
{
	internal static class PathMover
	{
		private static LinkedList<Path> paths = new LinkedList<Path>();

		public static void Add(FactionEntity fe, params Vector3[] positions) {
			paths.AddLast(new Path(fe, new Queue<Vector3>(positions)));
		}

		public static void Update(RealGameTime gameTime) {
			LinkedListNode<Path> cur = paths.First;
			while( cur != null ) {
				LinkedListNode<Path> next = cur.Next;
				if( !cur.Value.Finished ) {
					cur.Value.Update(gameTime);
				} else {
					paths.Remove(cur);
				}
				cur = next;
			}
		}

		private class Path
		{
			public readonly FactionEntity FactionEntity;
			public readonly Queue<Vector3> Positions;
			private bool finished = false;
			public bool Finished { get { return finished; } }
			private Vector3 direction;
			private Vector3 target;
			private const float step = 0.1f;

			public Path(FactionEntity fe, Queue<Vector3> positions) {
				this.FactionEntity = fe;
				this.Positions = positions;
				target = positions.Dequeue();
				direction = (target - FactionEntity.Position);
				direction.Normalize();
			}

			public void Update(RealGameTime gameTime) {
				if( Vector3.Distance(FactionEntity.Position, target) <= step ) {
					FactionEntity.Position = target;
					if( Positions.Count > 0 ) {
						target = Positions.Dequeue();
						direction = (target - FactionEntity.Position);
						direction.Normalize();
					} else {
						finished = true;
						FactionEntity.Enter();
					}
				} else {
					FactionEntity.Position += direction * step;
				}
				FactionEntity.Entity.UpdatePositionMatrix();
			}
		}
	}
}
